//
//  GameViewController.m
//  FightingGame
//
//  Created by iD Student on 6/25/13.
//  Copyright (c) 2013 iD Student. All rights reserved.
//

#import "GameViewController.h"

@interface GameViewController ()

@end

@implementation GameViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) loadGame
{
    timeRemaining = 30;
    score = 0;
    if (enemyList == nil)
    {
        enemyList = [[NSMutableArray alloc] initWithCapacity:0];
    }
    else
    {
        [enemyList removeAllObjects];
    }
    scoreLabel.text=@"Score: 0";
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(gameUpdate) userInfo:nil repeats:YES];
}

- (void) gameUpdate
{
    if (timeRemaining <= 0)
    {
        [self gameOver];
    }
    timeRemaining -= 0.25;
    if (timeRemaining % 2 == 0)
    {
        Enemy *enemy = [[Enemy alloc] init];
        enemy.imageView.center = CGPointMake(arc4random() % 280+20, arc4random() % 400+20);
        [enemyList addObject:enemy];
        [self.view addSubview:enemy.imageView];
        
        int count = self.view.subviews.count;
        count = count;
    }
    int i = 0;
    while (i<[enemyList count])
    {
        Enemy *enemy = [enemyList objectAtIndex:1];
        if (enemy.alive == NO)
        {
            [enemy.imageView removeFromSuperview];
            [enemyList removeObject:enemy];
        }
        else {
            i++;
        }
    }
}

- (void) gameOver
{
    [gameTimer invalidate];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over!" message: [[NSString alloc] initWithFormat:@"You scored: %d",score] delegate:self cancelButtonTitle:@"Main Menu" otherButtonTitles:nil];
    [alert show];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    for (Enemy *enemy in enemyList)
    {
        if (CGRectContainsPoint(enemy.imageView.frame, touchPoint))
        {
            if (enemy.alive == YES)
            {
                enemy.alive = NO;
                score += enemy.pointValue;
                scoreLabel.text = [NSString stringWithFormat:@"Score: %d",score];
            }
        }
    }
}


- (BOOL)shouldAutomaticallyForwardRotationMethods
{
    return YES;
}

- (BOOL)shouldAutomaticallyForwardAppearanceMethods
{
    return YES;
}

-(BOOL)shouldAutorotate
{
    NSLog(@"Called Autorotate");
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    NSLog(@"Called Supported in GameViewController");
    return UIInterfaceOrientationLandscapeLeft;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}

@end
